package leetcode.median;

/**
 * ClassName: $221_MaximalSquare
 * Description:
 * date: 2022-02-20 13:18
 *
 * @author liyifan
 */
public class $221_MaximalSquare {
    public int maximalSquare(char[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){return 0;}
        int row = matrix.length;
        int col = matrix[0].length;
        int maxSide = 0;
        for (int i = 0;i < row;i++) {
            for (int j = 0;j < col;j++) {
                if (matrix[i][j] == '1') {
                    // 找到一个可以作为正方形左上角的1
                    maxSide = Math.max(maxSide, 1);
                    int possMaxSide = Math.min(row - i, col - j);
                    // 分别向右和向下找
                    for (int k = 1;k < possMaxSide;k++) {
                        boolean flag = true;
                        if (matrix[i + k][j + k] == '0') {
                            break;
                        }
                        for (int m = 0;m < k;m++) {
                            if (matrix[i + k][j + m] == '0' || matrix[i + m][j + k] == '0'){
                                flag = false;
                                break;
                            }
                        }
                        if (flag) {
                            maxSide = Math.max(maxSide,  k + 1);
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        return maxSide * maxSide;
    }

    public int maximalSquareDP(char[][] matrix){
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){return 0;}
        int row = matrix.length;
        int col = matrix[0].length;
        int[][] dp = new int[row][col];
        int max = 0;
        for(int i = 0;i < row;i++){
            for (int j = 0;j < col;j++) {
                if (matrix[i][j] == '1') {
                    if (i == 0 || j == 0) {
                        dp[i][j] = 1;
                    } else {
                        dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) +  1;
                    }
                }
                max = Math.max(max, dp[i][j]);
            }
        }
        return max * max;
    }
}
